package com.qnzw.zjmy.ad;

import android.app.Activity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager;
import com.qnzw.zjmy.ad.inter.RewardAdFullAdInter;
import com.qnzw.zjmy.view.LoadingDailog;

import cn.hutool.core.util.ObjectUtil;

/**
 * 插屏广告
 */
public class MediationTablePlaqueAd {

    private String codeId;
    private RewardAdFullAdInter rewardAdFullAdInter;
    private TTFullScreenVideoAd ttFullScreenVideoAd;

    private boolean isAdReady = false; // 标志位，防止重复加载

    private MediationTablePlaqueAd() {
    }

    public static volatile MediationTablePlaqueAd instance;

    public static synchronized MediationTablePlaqueAd getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (MediationTablePlaqueAd.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new MediationTablePlaqueAd();
                }
            }
        }
        return instance;
    }

    public void init(String codeId) {
        this.codeId = codeId;
    }

    public void setRewardAdFullAdInter(RewardAdFullAdInter rewardAdFullAdInter) {
        this.rewardAdFullAdInter = rewardAdFullAdInter;
    }

    // 加载插全屏广告
    public void loadCacheInterstitialFullAd(Activity activity) {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity);
        adNativeLoader.loadFullScreenVideoAd(buildInterstitialFullAdSlot(), new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int errorCode, String errorMsg) {
                // 广告加载失败
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                // 广告加载成功
            }

            @Override
            public void onFullScreenVideoCached() {
                // 此API已废弃，直接使用带TTFullScreenVideoAd的回调
            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {
                // 广告缓存成功
                getInstance().ttFullScreenVideoAd = ttFullScreenVideoAd;
                isAdReady = true;  // 标记广告准备好
            }
        });
    }

    // 展示插全屏广告
    public void showCacheInterstitialFullAd(Activity activity, LoadingDailog loadingDailog) {
        if (activity == null || ttFullScreenVideoAd == null || !isAdReady) {
            loadInterstitialFullAd(activity, loadingDailog);  // 广告未准备好，重新加载广告
            return;
        }

        // 展示广告
        ttFullScreenVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
            @Override
            public void onAdShow() {
                // 广告展示
                MediationBaseManager manager = ttFullScreenVideoAd.getMediationManager();
                if (manager != null && manager.getShowEcpm() != null) {
                    MediationAdEcpmInfo showEcpm = manager.getShowEcpm();
                }
            }

            @Override
            public void onAdVideoBarClick() {
                // 广告点击
            }

            @Override
            public void onAdClose() {
                // 广告关闭
                if (ObjectUtil.isNotNull(rewardAdFullAdInter)) {
                    rewardAdFullAdInter.onAdClose();
                }
                onDestroy();
                loadCacheInterstitialFullAd(activity); // 广告关闭后继续加载下一个广告
            }

            @Override
            public void onVideoComplete() {
                // 广告视频播放完成
            }

            @Override
            public void onSkippedVideo() {
                // 广告跳过
            }
        });

        // 展示广告
        if (loadingDailog != null) {
            loadingDailog.dismiss();
        }
        ttFullScreenVideoAd.showFullScreenVideoAd(activity);
    }

    // 加载插全屏广告（如果广告尚未准备好）
    private void loadInterstitialFullAd(Activity activity, LoadingDailog loadingDailog) {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity);
        adNativeLoader.loadFullScreenVideoAd(buildInterstitialFullAdSlot(), new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int errorCode, String errorMsg) {
                if (loadingDailog != null) {
                    loadingDailog.dismiss();
                }
                // 广告加载失败
                if (ObjectUtil.isNotNull(rewardAdFullAdInter)) {
                    rewardAdFullAdInter.onError();
                }
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                // 广告加载成功
            }

            @Override
            public void onFullScreenVideoCached() {
                // 此API已废弃，直接使用带TTFullScreenVideoAd的回调
            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {
                // 广告缓存成功
                showInterstitialFullAd(activity, ttFullScreenVideoAd, loadingDailog);
            }
        });
    }

    // 展示插全屏广告（在缓存后展示）
    private void showInterstitialFullAd(Activity activity, TTFullScreenVideoAd ttFullScreenVideoAd, LoadingDailog loadingDailog) {
        if (activity == null || ttFullScreenVideoAd == null) {
            return;
        }

        // 展示广告
        ttFullScreenVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
            @Override
            public void onAdShow() {
                // 广告展示
                MediationBaseManager manager = ttFullScreenVideoAd.getMediationManager();
                if (manager != null && manager.getShowEcpm() != null) {
                    MediationAdEcpmInfo showEcpm = manager.getShowEcpm();
                }
            }

            @Override
            public void onAdVideoBarClick() {
                // 广告点击
            }

            @Override
            public void onAdClose() {
                // 广告关闭
                if (ObjectUtil.isNotNull(rewardAdFullAdInter)) {
                    rewardAdFullAdInter.onAdClose();
                }
                onDestroy();
                loadCacheInterstitialFullAd(activity); // 广告关闭后继续加载下一个广告
            }

            @Override
            public void onVideoComplete() {
                // 广告视频播放完成
            }

            @Override
            public void onSkippedVideo() {
                // 广告跳过
            }
        });

        if (loadingDailog != null) {
            loadingDailog.dismiss(); // 确保在展示广告时关闭 loading
        }

        ttFullScreenVideoAd.showFullScreenVideoAd(activity);  // 展示插全屏广告
    }

    // 构造插全屏广告的 AdSlot
    private AdSlot buildInterstitialFullAdSlot() {
        return new AdSlot.Builder()
                .setCodeId(codeId)   // 广告位ID
                .setAdCount(3)        // 广告展示数量
                .setOrientation(TTAdConstant.VERTICAL)  // 设置广告方向，竖屏
                .setMediationAdSlot(new MediationAdSlot.Builder().setMuted(false).build())  // 设置广告的沉默状态
                .build();
    }

    // 清理资源，销毁广告实例
    private void onDestroy() {
        if (ttFullScreenVideoAd != null) {
            TTFullScreenVideoAd ad = ttFullScreenVideoAd;
            if (ad.getMediationManager() != null) {
                ad.getMediationManager().destroy();  // 销毁广告管理器
            }
            ttFullScreenVideoAd = null;
        }
    }
}

